package at.bherbst.udp;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ForwardServer extends Activity implements OnClickListener {
	private static final String TAG = "FarwardServer";
	private Button buttonStart, buttonStop, applyButton;
	private EditText text_serverip;
	private EditText text_serverip_incoming;

	private static SharedPreferences settings;
	private static SharedPreferences.Editor editor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		settings = this.getSharedPreferences("udpserver", MODE_WORLD_WRITEABLE);
		// get value
		// will return "0" if preference not exists, else return stored value
		String serverip = settings.getString("serverip",  "please enter Target-IP");
		Toast.makeText(this, "loaded " + serverip, Toast.LENGTH_LONG).show();
		text_serverip = (EditText) this.findViewById(R.id.editText1);
		text_serverip.setText(serverip);
		
		String serverip_incoming = settings.getString("serverip_incoming", "please enter incoming interface IP" );
		text_serverip_incoming = (EditText) this.findViewById(R.id.editText2);
		text_serverip_incoming.setText(serverip_incoming);

		applyButton = (Button) this.findViewById(R.id.button1);
		applyButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				updateText();
			}
		});

		buttonStart = (Button) findViewById(R.id.buttonStart);
		buttonStop = (Button) findViewById(R.id.buttonStop);
		buttonStart.setOnClickListener(this);
		buttonStop.setOnClickListener(this);
	}

	public void onClick(View src) {
		switch (src.getId()) {
		case R.id.buttonStart:
			Log.d(TAG, "onClick: starting service");
			this.startService(new Intent(this, MyService.class));
			break;
		case R.id.buttonStop:
			Log.d(TAG, "onClick: stopping service");
			stopService(new Intent(this, MyService.class));
			break;
		}
	}

	private void updateText() {
		editor = settings.edit();
		// store value
		editor.putString("serverip", text_serverip.getText() + "");
		editor.putString("serverip_incoming", text_serverip_incoming.getText() + "");
		editor.commit();
		Toast.makeText(this, "Target-IP and Mobile incoming IP saved.", Toast.LENGTH_SHORT).show();
	}
}